﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Annotations;
using System.Windows.Shapes;

namespace AVCConvert.Models
{
    public partial class MainViewModel:ObservableObject
    {
        public Logger Logger { get; set; }

        private string dir = @"D:/Convert/";

        //private string path = @"D:/Convert/" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".avc";

        //private string pathX8 = @"D:/Convert/" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")+ "(X8 To X1)" + ".avc";

        private string selectedFilePath;

        [ObservableProperty]
        private bool convertX8;
        [ObservableProperty]
        private bool convertX4;
        [ObservableProperty]
        private bool convertX2;

        [ObservableProperty]
        private bool convertX8CBEnable = false;
        [ObservableProperty]
        private bool convertX4CBEnable = false;
        [ObservableProperty]
        private bool convertX2CBEnable = false;

        [ObservableProperty]
        private bool importFileEnable = true;
        [ObservableProperty]
        private bool convertX8BtEnable;
        [ObservableProperty]
        private bool convertX4BtEnable;
        [ObservableProperty]
        private bool convertX2BtEnable;
        [ObservableProperty]
        private bool compressFileEnable;

        private void isEnable(bool isTrue=false) 
        {
            ConvertX8BtEnable = isTrue;
            ConvertX4BtEnable = isTrue;
            ConvertX2BtEnable = isTrue;
            CompressFileEnable = isTrue;
        }
        public MainViewModel()
        {
            Logger = new Logger();
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            /*if (File.Exists(path)) throw new Exception($"文件路径{path}已存在");
            if (path != null) this.path = path;*/
            /*File.Create(dir + this.path).Close();
            this.path = dir + this.path;*/
        }


        #region 导入文件操作
        [RelayCommand]
        public async void ImportFile()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "AVC Files(*.avc*)|*.avc*|All Files(*.*)|*.*",
                Title = "请选择文件"
            };
            if (openFileDialog.ShowDialog() == true) 
            {
                selectedFilePath = openFileDialog.FileName;
                await ImportData(openFileDialog.FileName);
                isEnable(true);
                //ConvertFile(openFileDialog.FileName);
                //CompressFile(openFileDialog.FileName);
            }
            else
            {
                Logger.WriteLog("未选择任何文件");
            }
        }

        private async Task ImportData(string filepath)
        {
            Logger.WriteLog("[" + DateTime.Now + "]" + "导入文件中......");
            ImportFileEnable = false;
            //导入后的数据处理逻辑
            //int lineCount = File.ReadLines(filepath).Count();
            try
            {
                //var lines = await ReadLinesAsync(filepath);
                //int lineCount = lines.Count();//读取导入文件行数
                Logger.WriteLog("[" + DateTime.Now + "]" + $"文件{selectedFilePath}" + "导入成功.....");
               // Logger.WriteLog($"文件的行数是：{lineCount}");
            }
            catch (Exception ex)
            {
                Logger.WriteLog($"发送错误:{ex.Message}");
            }
            finally 
            {
                ImportFileEnable = true;
            }
        }
        private async Task<IEnumerable<string>> ReadLinesAsync(string filepath)
        {
            var lines = new List<string>();
            using (StreamReader reader = new StreamReader(filepath)) 
            {
                string line;
                while ((line =await reader.ReadLineAsync()) != null) 
                { 
                    lines.Add(line); 
                }
            }
            return lines;
        }
        #endregion

        #region X8 To X1 展开操作
        //X8转换成X1
        [RelayCommand]
        private async void ConvertX8File(string filepath)
        {
            string pathX8 = @"D:/Convert/" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "(X8 To X1)" + ".avc";
            ConvertX8BtEnable = false ;
            Logger.WriteLog("[" + DateTime.Now + "]" + "文件转换 | X8 To X1......");
            List<string> expandData = new List<string>();
            string firstLine = null;
            try
            {
                await Task.Run(async () => 
                {
                    using (StreamReader reader = new StreamReader(selectedFilePath))
                    {
                        firstLine = await reader.ReadLineAsync();
                        expandData.Add(firstLine);
                        while (!reader.EndOfStream)
                        {
                            string line = await reader.ReadLineAsync();
                            if (line == null)
                            {
                                break;
                            }
                            line = line.Trim(';');
                            string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//使用空格把字符串分割成多个部分

                            for (int i = 1; i < parts.Length; i++)
                            {
                                if(parts[i].Length == 8)
                                {
                                    //Logger.WriteLog(parts[i]);
                                    foreach(char c in parts[i])//遍历提取长度为8的元素
                                    {
                                        //Logger.WriteLog($"长度为8的数据：{c}");
                                        string[] newParts = new string[parts.Length];
                                        parts.CopyTo(newParts, 0);

                                        newParts[i] = c.ToString();
                                        //Logger.WriteLog(newParts[i]);
                                        StringBuilder sb = new StringBuilder();
                                        for(int j = 0; j < newParts.Length; j++)
                                        {
                                            if(j > 0) sb.Append(' ');
                                            sb.Append(newParts[j]);
                                        }
                                        sb.Append(';');
                                        expandData.Add(sb.ToString());
                                    }
                                }
                            }
                            //固定位置X8转X1代码
                            /*if (parts.Length > 0)
                            {
                                string rPart = parts[0];//提取R(Number)
                                int count = int.Parse(rPart.Substring(1));//提取Number
                                string lastCoulumn = parts[parts.Length - 1];//提取最后一列,数组元素从0开始，n-1为最后一个元素
                                if (lastCoulumn.EndsWith(";"))
                                {
                                    lastCoulumn = lastCoulumn.Substring(0, lastCoulumn.Length - 1);
                                }
                                for (int i = 0; i < lastCoulumn.Length; i++) //通过最后一列的长度循环
                                {
                                    StringBuilder sb = new StringBuilder();
                                    for (int j = 0; j < parts.Length - 1; j++)// 拼接除最后一个字段外的所有字段
                                    {
                                        sb.Append(' ');
                                        sb.Append(parts[j]);
                                    }
                                    sb.Append(' ');
                                    sb.Append(lastCoulumn[i]);
                                    sb.Append(';');
                                    expandData.Add(sb.ToString());
                                }
                            }*/
                        }
                    }
                    using (StreamWriter writer = new StreamWriter(pathX8))
                    {
                        foreach (string line in expandData)
                        {
                            await writer.WriteLineAsync(line);
                        }
                        Logger.WriteLog("[" + DateTime.Now + "]" + "X8 To X1展开完成......");
                        Logger.WriteLog($"文件已保存到{pathX8}");
                    }
                });
            }
            catch (Exception ex) 
            {
                Logger.WriteLogAsync($"发生错误{ex.Message}");
            }
            finally
            {
                ConvertX8BtEnable = true ;
            }
            
        }
        #endregion

        #region X4 To X1 展开操作
        //X4转换成X1
        [RelayCommand]
        private async void ConvertX4File(string filepath)
        {
            Logger.WriteLog("[" + DateTime.Now + "]" + "文件转换 | X4 To X1......");
            string pathX4 = @"D:/Convert/" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "(X4 To X1)" + ".avc";
            ConvertX4BtEnable = false;
            List<string> expandData = new List<string>();
            string firstLine = null;
            try
            {
                await Task.Run(async () =>
                {
                    using (StreamReader reader = new StreamReader(selectedFilePath))
                    {
                        firstLine = await reader.ReadLineAsync();
                        expandData.Add(firstLine);
                        while (!reader.EndOfStream)
                        {
                            string line = await reader.ReadLineAsync();
                            if (line == null)
                            {
                                break;
                            }
                            line = line.Trim(';');
                            string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//使用空格把字符串分割成多个部分
                            for (int i = 1; i < parts.Length; i++)
                            {
                                if (parts[i].Length == 4)
                                {
                                    foreach (char c in parts[i])
                                    {
                                        string[] newParts = new string[parts.Length];
                                        parts.CopyTo(newParts, 0);

                                        newParts[i] = c.ToString();
                                        StringBuilder sb = new StringBuilder();
                                        for (int j = 0; j < newParts.Length; j++)
                                        {
                                            if (j > 0) sb.Append(' ');
                                            sb.Append(newParts[j]);
                                        }
                                        sb.Append(';');
                                        expandData.Add(sb.ToString());
                                        expandData.Add(sb.ToString());
                                    }
                                }
                            }
                            //固定位置X4转X1代码
                            /*if (parts.Length > 0)
                            {
                                string rPart = parts[0];//提取R(Number)
                                int count = int.Parse(rPart.Substring(1));//提取Number
                                string lastCoulumn = parts[parts.Length - 1];//提取最后一列,数组元素从0开始，n-1为最后一个元素
                                if (lastCoulumn.EndsWith(";"))
                                {
                                    lastCoulumn = lastCoulumn.Substring(0, lastCoulumn.Length - 1);
                                }
                                for (int i = 0; i < lastCoulumn.Length; i++) //通过最后一列的长度循环
                                {
                                    StringBuilder sb = new StringBuilder();
                                    //sb.Append(rPart);
                                    for (int j = 0; j < parts.Length - 2; j++)// 拼接除最后两个个字段外的所有字段
                                    {
                                        sb.Append(' ');
                                        sb.Append(parts[j]);
                                        sb.Append(' ');
                                    }
                                    if (parts[8].Length == 4)
                                    {
                                        if (i < 2)
                                        {
                                            sb.Append(parts[8][0]);
                                            sb.Append(' ');
                                        }
                                        else if (i < 4) 
                                        {
                                            sb.Append(parts[8][1]);
                                            sb.Append(' ');
                                        }else if (i < 6)
                                        {
                                            sb.Append(parts[8][2]);
                                            sb.Append(' ');
                                        }else if (i < 8)
                                        {
                                            sb.Append(parts[8][3]);
                                            sb.Append(' ');
                                        }
                                        sb.Append(' ');
                                    }
                                    else
                                    {
                                        Logger.WriteLog("数据位数不为4");
                                        return;
                                    }
                                    sb.Append(' ');
                                    sb.Append(lastCoulumn[i]);
                                    sb.Append(';');
                                    expandData.Add(sb.ToString());
                                }
                            }*/
                        }
                    }
                    using (StreamWriter writer = new StreamWriter(pathX4))
                    {
                        foreach (string line in expandData)
                        {
                            await writer.WriteLineAsync(line);
                        }
                        Logger.WriteLog("[" + DateTime.Now + "]" + "X2 To X1展开完成......");
                        Logger.WriteLog($"文件已保存到{pathX4}");
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.WriteLogAsync($"发生错误{ex.Message}");
            }
            finally
            {
                ConvertX4BtEnable = true;
            }
        }
        #endregion

        #region X2 To X1 展开操作
        //X2转换成X1
        [RelayCommand]
        private async void ConvertX2File(string filepath)
        {
            string pathX2 = @"D:/Convert/" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "(X2 To X1)" + ".avc";
            ConvertX2BtEnable = false;
            Logger.WriteLog("[" + DateTime.Now + "]" + "文件转换 | X2 To X1......");
            List<string> expandData = new List<string>();
            string firstLine = null;
            try
            {
                await Task.Run(async () =>
                {
                    using (StreamReader reader = new StreamReader(selectedFilePath))
                    {
                        firstLine = await reader.ReadLineAsync();
                        expandData.Add(firstLine);
                        while (!reader.EndOfStream)
                        {
                            string line = await reader.ReadLineAsync();
                            if (line == null)
                            {
                                break;
                            }
                            line = line.Trim(';');
                            string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//使用空格把字符串分割成多个部分
                            for (int i = 1; i < parts.Length; i++)
                            {
                                if (parts[i].Length == 2)
                                {
                                    foreach (char c in parts[i])
                                    {
                                        string[] newParts = new string[parts.Length];
                                        parts.CopyTo(newParts, 0);

                                        newParts[i] = c.ToString();
                                        StringBuilder sb = new StringBuilder();
                                        for (int j = 0; j < newParts.Length; j++)
                                        {
                                            if (j > 0) sb.Append(' ');
                                            sb.Append(newParts[j]);
                                        }
                                        sb.Append(';');
                                        expandData.Add(sb.ToString());
                                        expandData.Add(sb.ToString());
                                        expandData.Add(sb.ToString());
                                        expandData.Add(sb.ToString());
                                    }
                                }
                            }
                            //固定位置X2转X1代码
                            /*string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//使用空格把字符串分割成多个部分
                            if (parts.Length > 0)
                            {
                                string rPart = parts[0];//提取R(Number)
                                int count = int.Parse(rPart.Substring(1));//提取Number
                                string lastCoulumn = parts[parts.Length - 1];//提取最后一列,数组元素从0开始，n-1为最后一个元素
                                if (lastCoulumn.EndsWith(";"))
                                {
                                    lastCoulumn = lastCoulumn.Substring(0, lastCoulumn.Length - 1);
                                }
                                for (int i = 0; i < lastCoulumn.Length; i++) //通过最后一列的长度循环
                                {
                                    StringBuilder sb = new StringBuilder();
                                    //sb.Append(rPart);
                                    for (int j = 0; j < parts.Length - 3; j++)// 拼接除最后三个字段外的所有字段
                                    {
                                        sb.Append(' ');
                                        sb.Append(parts[j]);
                                        sb.Append(' ');
                                    }
                                    if (parts[7].Length == 2)
                                    {
                                        if (i < 4)
                                        {
                                            sb.Append(parts[7][0]);
                                            sb.Append(' ');
                                        }
                                        else
                                        {
                                            sb.Append(parts[7][1]);
                                            sb.Append(' ');
                                        }
                                        sb.Append(' ');
                                    }
                                    else
                                    {
                                        Logger.WriteLog("数据位数不为2");
                                        return;
                                    }
                                    sb.Append(' ');
                                    sb.Append("X");
                                    sb.Append(' ');
                                    sb.Append(lastCoulumn[i]);
                                    sb.Append(';');
                                    expandData.Add(sb.ToString());
                                }
                            }*/
                        }
                    }
                    using (StreamWriter writer = new StreamWriter(pathX2))
                    {
                        foreach (string line in expandData)
                        {
                            await writer.WriteLineAsync(line);
                        }
                        Logger.WriteLog("[" + DateTime.Now + "]" + "X2 To X1展开完成......");
                        Logger.WriteLog($"文件已保存到{pathX2}");
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.WriteLogAsync($"发生错误{ex.Message}");
            }
            finally
            {
                ConvertX2BtEnable = true;
            }
        }
        #endregion

        #region R压缩操作
        //R压缩
        [RelayCommand]
        private async void CompressFile()
        {
            string path = @"D:/Convert/" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".avc";
            CompressFileEnable = false;
            Logger.WriteLog("[" + DateTime.Now + "]" + "压缩文件......");
            List<string> compressedData = new List<string>();
            string firstLine = null;
            string previousLine = null;//前一行数据
            string[] previousParts = null;//前一行RN之后的数据
            int count = 0;
            try
            {
                using (StreamReader reader = new StreamReader(selectedFilePath))
                {
                    // 跳过第一行
                    firstLine = await reader.ReadLineAsync();
                    compressedData.Add(firstLine);
                    while (!reader.EndOfStream)
                    {
                        string currentLine =await reader.ReadLineAsync();
                        if (currentLine == null)
                        {
                            break;
                        }
                        //用空格将其拆分成数组（currentParts）
                        string[] currentParts = currentLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        if (previousLine == null)
                        {
                            previousLine = currentLine;
                            previousParts = currentParts;
                            count = int.Parse(currentParts[0].Substring(1));
                        }
                        else if (AreLinesEquivalent(previousParts, currentParts))
                        {
                            count += int.Parse(currentParts[0].Substring(1));
                        }
                        else
                        {

                            if (count > 0)
                            {
                                compressedData.Add(CompressLine(previousParts, count));
                            }
                            else
                            {
                                compressedData.Add(previousLine);
                            }
                            previousLine = currentLine;
                            previousParts = currentParts;
                            count = int.Parse(currentParts[0].Substring(1));
                        }
                    }
                    // 处理最后一组数据
                    if (previousLine != null)
                    {
                        if (count > 1)//重复的话就增加计数
                        {
                            compressedData.Add(CompressLine(previousParts, count));
                        }
                        else
                        {
                            compressedData.Add(previousLine);//不重复的行直接添加
                        }
                    }
                }

                using (StreamWriter writer = new StreamWriter(path))
                {
                    foreach (string line in compressedData)
                    {
                        await writer.WriteLineAsync(line);
                    }
                }
                Logger.WriteLog("[" + DateTime.Now + "]" + "压缩完成......");
                Logger.WriteLog($"文件已保存到{path}");
            }
            catch (Exception ex) 
            {
                Logger.WriteLog($"出现错误：{ex.Message}");
            }
            finally
            {
                CompressFileEnable = true ;
            }
            
        }
        /*static List<string> Compress(List<string> data)
        {
            List<string> compressedData = new List<string>();
            if (data.Count == 0)
            {
                return compressedData;
            }
            string previousLine = data[0];
            string[] previousParts = previousLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            int count = 1;
            for (int i = 1; i < data.Count; i++)
            {
                string currentLine = data[i];
                string[] currentParts = currentLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (AreLinesEquivalent(previousParts, currentParts))
                {
                    count++;
                }
                else
                {
                    compressedData.Add(CompressLine(previousParts, count));
                    previousLine = currentLine;
                    previousParts = currentParts;
                    count = 1;
                }
            }
            // 处理最后一组数据
            compressedData.Add(CompressLine(previousParts, count));
            return compressedData;
        }*/
        static bool AreLinesEquivalent(string[] parts1, string[] parts2)
        {
            //string[] parts1 = line1.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            //string[] parts2 = line2.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (parts1.Length != parts2.Length)
            {
                return false;
            }
            for (int i = 1; i < parts1.Length; i++) // 从索引 1 开始比较，因为 R 后面的数据才需要比较
            {
                if (parts1[i] != parts2[i])
                {
                    return false;
                }
            }
            return true;
        }

        static string CompressLine(string[] parts, int count)
        {
            //string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder sb = new StringBuilder();
            sb.Append($"R{count}"); //提取RN
            for (int i = 1; i < parts.Length; i++) // 从索引 1 开始添加，因为 R 后面的数据需要保留
            {
                sb.Append(" ");
                sb.Append(parts[i]);
            }
            return sb.ToString();
        }
        #endregion

        [RelayCommand]
        private void CleanLog()
        {
            Logger.Logs.Clear();
        }
        [RelayCommand]
        private void OpenFolder()
        {
            string path = @"D:\Convert\";
            Process.Start("explorer",path);
        }
        /*private void SaveFile(string filepath,List<string> data)
        {
            File.WriteAllLines(filepath, data);
        }*/
    }
}
